import { Injectable } from '@nestjs/common';
import PageDto from './dto/page.dto';
import { User } from '@app/db/entity/User';
import { DbService } from '../../db/db.service';
import { ConfigureService } from '@app/configure';
import { CacheService } from '@app/cache';
import { DataSource, FindOptionsWhere, In, Like } from 'typeorm';
import { UserGroup } from '@app/db/entity/UserGroup';

@Injectable()
export class UserService {
    constructor(
        private readonly db:DbService,
    ){}


    async page(dto:PageDto) {
        let result:PaginationResult<User & {group?:UserGroup, parent?:User}> = {
            total : 0,
            rows : []
        }

        let where:FindOptionsWhere<User> = {
            
        }

        if(dto.groupId) {
            where.groupId = dto.groupId
        }

        if(dto.enable !== undefined) {
            where.enable = dto.enable
        }


        if(dto.account) {
            where.account = dto.account
        }

        
        result.total = await this.db.user.count(where)

        if(result.total > 0) {
            result.rows = await this.db.user.pagination(dto.pageNo, dto.pageSize, where, null, {id : 'DESC'})
            const groupIds:number[] = []
            const parentIds:number[] = []
            result.rows.forEach(row => {
                if(row.groupId > 0 && !groupIds.includes(row.groupId)) {
                    groupIds.push(row.groupId)
                }

                if(row.directParent > 0 && !parentIds.includes(row.directParent)) {
                    parentIds.push(row.directParent)
                }
            })
            
            let groups:UserGroup[] = []
            let parents:User[] = []

            if(groupIds.length > 0) {
                groups = await this.db.userGroup.find({id: In(groupIds)}, {name:true, id:true})
            }

            if(parentIds.length > 0) {
                parents = await this.db.user.find({id: In(parentIds)}, {account:true, id:true})
            }
            

            result.rows.forEach(row => {
                delete row.password
                delete row.salt

                const group = groups.find(v => v.id == row.groupId)
                if(group) {
                    row.group = group
                }

                const p = parents.find(v => v.id == row.directParent)
                if(p) {
                    row.parent = p
                }
                
            })



            
        }



        return result
    }

    


    async del(id:number) {
        let row = await this.db.user.findOne({ id }, {id: true})
        if(!row) return

        return this.db.user.delete({id : id})
    }


    async enable(id:number) {
        this.db.user.update({id: id}, {enable: true})

        return true
    }

    async forbid(id:number) {
        this.db.user.update({id: id}, {enable: false})

        return true
    }
    
}
